class HunterUnion {
  constructor() {
    this.topics = {};
    console.log("实例化工会");
  }
  publish(topic, money) {
    if (!this.topics[topic]) {
      return;
    }
    for (let fn of this.topics[topic]) {
      fn(money);
    }
  }
  subscribe(topic, fn) {
    if (!this.topics[topic]) {
      this.topics[topic] = [];
    }
    this.topics[topic].push(fn);
  }
  unSubscribe(topic, fn) {
    if (!this.topics[topic]) {
      return;
    }
    const idnex = this.topics[topic].findIndex((f) => f === fn);
    return this.topics[topic].splice(idnex, 1);
  }
}

let Sigleton = (function () {
  var instance;
  function init() {
    return new HunterUnion();
  }
  return {
    getInstance: () => {
      if (!instance) {
        instance = init();
      }
      return instance;
    },
  };
})();

class Hunter {
  constructor(name) {
    console.log("实例化hunter");
    this.name = name;
    this.hu = Sigleton.getInstance();
  }
  publish(topic, money) {
    this.hu.publish(topic, money);
  }
  subscribe(topic, fn) {
    this.hu.subscribe(topic, fn);
  }
}

const h1 = new Hunter();
const h2 = new Hunter();

h1.subscribe("tiger", (e) => {
  console.log("有人发布了讨伐tiger" + e + "金");
});
h1.publish("tiger", 200);
h1.publish("tiger", 100);
